/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-11-19 10:32:50
 * 天凉好个秋
 */


import Schema, { Rules, Values } from "async-validator"
import { Context } from "koa"
import requestParams from "./requestParams"

/**
 * @description: 
 * @param {*} T 校验通过返回的数据结构
 * @param {Context} ctx
 * @param {Rules} rules 表单校验规则
 * @param {Boolean} allError 校验失败时是否返回全部错误信息，默认只返回第一条
 * @return {*}  T
 */
const vaildate = async <T extends Values>(ctx: Context, rules: Rules, allError: boolean = false): Promise<{data: T, error: null | any}> => {
    const validator = new Schema(rules)
    const formData = requestParams(ctx)
    return await validator.validate(formData).then((res) => {
        return {
            data: res as T,
            error: null
        }
    }).catch(error => {
        return {
            data: {} as T,
            error: allError ? error.errors : error.errors[0].message
        }
    })
}

export default vaildate